package com.atguigu.gmall.pay.controller;

import com.alipay.api.AlipayApiException;
import com.atguigu.gmall.common.constans.MqConstant;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.feign.order.OrderFeign;
import com.atguigu.gmall.pay.service.PayService;
import com.atguigu.gmall.pay.vo.PayNotifySuccessVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/9/16 1:12
 */
@Slf4j
@RestController
@RequestMapping("/api/payment")
public class PaySuccessController {
    @Autowired
    PayService payService;
    @Autowired
    OrderFeign orderFeign;
    @Autowired
    RabbitTemplate   rabbitTemplate;
    @PostMapping("/notify/success")
    public String paySuccess(@RequestParam Map<String, String> params, PayNotifySuccessVo vo) throws AlipayApiException {
        /**
         * 异步通知处理逻辑
         * 程序执行完需要打印输出"success"，否则支付宝会一直发送通知
         **/
        Boolean flag=payService.checkAliPaySign(params);
        if (flag){
            log.info("支付成功,对外交易号：{}",vo.getOut_trade_no());
            //调用mq发送消息,保证消息的最终一致性
            // 更新订单状态为已支付
           // Result result = orderFeign.updateOrderStatusToPaid(vo.getOut_trade_no())
            rabbitTemplate.convertAndSend(MqConstant.ORDER_EVENT_EXCHANGE,
                    MqConstant.ORDER_STATUS_PAID_ROUTING_KEY,
                    vo.getOut_trade_no());
            log.info("发送消息成功,更新订单状态为已支付成功");
            return "success";
        }
        log.error("支付失败,对外交易号：{}",vo.getOut_trade_no());
        return "error";
    }

    @PostConstruct
    public void initRabbitTemplate(){
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause)->{
            if (ack){
                if (correlationData!=null){
                    log.info("消息发送成功, 编号：{}", correlationData.getId());
                }else {
                    log.info("消息发送成功");
                }
            }else {
                log.error("消息发送失败,原因：{}",cause);
            }
        });
    }
}
